package com.hdu.kdk_es_orm.wrapper;


import com.hdu.kdk_es_orm.core.QueryFilter;
import lombok.val;

import java.util.Arrays;
import java.util.stream.Collectors;

import static com.hdu.kdk_es_orm.core.FilterType.NESTED;

/**
 * 帮助构建 wrapper之间的 || &&
 */
public class EsWrapperLogicHelper {

    public enum LogicOp {
        AND,
        OR
    }

    @SafeVarargs
    public static <T> EsWrapper<T> and(EsWrapper<T>... wrappers) {
        return createCombinedWrapper(LogicOp.AND, wrappers);
    }

    @SafeVarargs
    public static <T> EsWrapper<T> or(EsWrapper<T>... wrappers) {
        return createCombinedWrapper(LogicOp.OR, wrappers);
    }

    @SafeVarargs
    private static <T> EsWrapper<T> createCombinedWrapper(LogicOp logicOp, EsWrapper<T>... wrappers) {

        val firstWrapper = wrappers[0];

        val totalQueryFilter = new QueryFilter();
        totalQueryFilter.setType(NESTED);

        val mustOrShouldList = Arrays.stream(wrappers)
                .map(EsWrapper::getQueryFilter)
                .collect(Collectors.toList());

        switch (logicOp) {
            case AND:
                totalQueryFilter.setMust(mustOrShouldList);
                break;
            case OR:
                totalQueryFilter.setShould(mustOrShouldList);
                break;
            default:
                throw new IllegalArgumentException("Unsupported LogicOp: " + logicOp);
        }

        firstWrapper.setQueryFilter(totalQueryFilter);

        return firstWrapper;
    }
}

